/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var diameterOfBinaryTree = function (root) {
    let maxDiameter = 0
    const iter = function (node) {
        if (node.left == null && node.right == null) return 0
        let maxLeft = 0, maxRight = 0
        if (node.left)
            maxLeft = iter(node.left) + 1
        if (node.right)
            maxRight = iter(node.right) + 1
        if (maxLeft + maxRight > maxDiameter) maxDiameter = maxLeft + maxRight
        return maxLeft > maxRight ? maxLeft : maxRight
    }
    iter(root)
    return maxDiameter
};